<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule"
        @keyup.enter="onSubmit">
        <el-form-item label="创建日期" prop="createdAt">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期"
            :disabled-date="time => searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
          —
          <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期"
            :disabled-date="time => searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
        </el-form-item>

        <el-form-item label="销售方名称" prop="sellerName">
          <el-input v-model="searchInfo.sellerName" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="购买方名称" prop="buyerName">
          <el-input v-model="searchInfo.buyerName" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="购买方税号" prop="buyerIdNum">
          <el-input v-model="searchInfo.buyerIdNum" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="购买方账号" prop="buyerBankAccNum">
          <el-input v-model="searchInfo.buyerBankAccNum" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="searchInfo.remark" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="回写发票号" prop="eiId">
          <el-input v-model="searchInfo.eiId" placeholder="搜索条件" />
        </el-form-item>

        <template v-if="showAllQuery">
          <!-- 将需要控制显示状态的查询条件添加到此范围内 -->
        </template>

        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button link type="primary" icon="arrow-down" @click="showAllQuery = true"
            v-if="!showAllQuery">展开</el-button>
          <el-button link type="primary" icon="arrow-up" @click="showAllQuery = false" v-else>收起</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button v-auth="btnAuth.add" type="primary" icon="plus" @click="openDialog()">新增</el-button>
        <el-button v-auth="btnAuth.batchDelete" icon="delete" style="margin-left: 10px;"
          :disabled="!multipleSelection.length" @click="onDelete">删除</el-button>
        <ExportTemplate v-auth="btnAuth.exportTemplate" template-id="fapiao_InvoiceItemUsages" />
        <ExportExcel v-auth="btnAuth.exportExcel" template-id="fapiao_InvoiceItemUsages" :condition="{ids: multipleSelection.map(item => item.ID).join(',')}" />
        <ImportExcel v-auth="btnAuth.importExcel" template-id="fapiao_InvoiceItemUsages" @on-success="getTableData" />
      </div>
      <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID"
        @selection-change="handleSelectionChange" border show-overflow-tooltip>
        <el-table-column type="selection" width="55" />

        <el-table-column align="left" label="日期" prop="createdAt" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>

        <el-table-column align="left" label="销售方名称" prop="sellerName" width="120" />
        <el-table-column align="left" label="购买方名称" prop="buyerName" width="120" />
        <el-table-column align="left" label="购买方税号" prop="buyerIdNum" width="120" />
        <el-table-column align="left" label="购买方账号" prop="buyerBankAccNum" width="120" />
        <el-table-column align="left" label="备注" prop="remark" width="120" />
        <el-table-column align="left" label="回写发票号" prop="eiId" width="120" />
        <el-table-column align="left" label="PDF" prop="pdf" width="120">
          <template #default="scope">
            <el-link :href="scope.row.pdf" target="_blank" type="primary" v-if="scope.row.pdf">点击下载</el-link>
          </template>
        </el-table-column>
        <el-table-column align="left" label="XML" prop="xml" width="120">
          <template #default="scope">
            <el-link :href="scope.row.xml" target="_blank" type="primary" v-if="scope.row.xml">点击下载</el-link>
          </template>
        </el-table-column>
        <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith"
          :show-overflow-tooltip="false">
          <template #default="scope">
            <el-button v-auth="btnAuth.info" type="primary" link class="table-button"
              @click="updateInvoiceItemUsagesFunc(scope.row, true)"><el-icon style="margin-right: 5px">
                <InfoFilled />
              </el-icon>查看</el-button>
            <el-button v-auth="btnAuth.edit" type="primary" link icon="edit" class="table-button"
              @click="updateInvoiceItemUsagesFunc(scope.row, false)" v-if="scope.row.examine == 0">编辑</el-button>
            <el-popconfirm :title="`确认${scope.row.examine == 0 ? '提交审核' : '提交开票'}吗?`" placement="top-start"
              @confirm="examineBtnClick(scope, Number(scope.row.examine) + 1)" v-if="scope.row.examine <= 1">
              <template #reference>
                <el-button v-auth="btnAuth.audit" type="primary" link icon="Check">{{
                  examineTypeName[scope.row.examine] }} </el-button>
              </template>
            </el-popconfirm>
            <el-button v-auth="btnAuth.audit" type="primary" link disabled icon="Check"
              v-if="(scope.row.examine == 2 && !scope.row.task) || scope.row.examine == 3">{{
                examineTypeName[scope.row.examine] }}</el-button>
            <template v-if="(scope.row.examine == 2 && scope.row?.task)">
              <el-tooltip effect="dark"
                :content="scope.row?.task?.task_state == 3 ? scope.row.task?.task_msg : scope.row.task?.invoice_list_message"
                placement="top-start" :disabled="!scope.row.task?.task_msg || !scope.row.task?.invoice_list_message">
                <el-button v-auth="btnAuth.audit" type="primary" link icon="Check" @click="taskBtnClick(scope)">{{
                  taskName[`${scope.row.task?.task_state}`] }}</el-button></el-tooltip>
            </template>
            <el-button v-auth="btnAuth.audit" type="primary" link v-if="scope.row.examine == 1"
              @confirm="examineBtnClick(scope, 0)">取消审核</el-button>
            <el-button v-auth="btnAuth.delete" type="primary" link @click="deleteRow(scope.row)" style="color: red;"
              v-if="Number(scope.row.examine) < 2">
              <el-icon style="color: red;margin-right: 5px;">
                <delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]" :total="total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog destroy-on-close v-model="dialogFormVisible" fullscreen :show-close="false" :before-close="closeDialog"
      :close-on-click-modal="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg" v-if="!isDisabled">{{ type === 'create' ? '新增' : '编辑' }}</span>
          <span class="text-lg" v-else>查看详情</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="enterDialog" v-if="!isDisabled">保 存</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </div>
      </template>

      <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px"
        :disabled="isDisabled">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售方名称:" prop="sellerName">
              <el-select v-model="formData.sellerName" placeholder="请选择销售方名称">
                <el-option v-for="item in sellerNameSelectOptions" :key="item.value" :label="item.label"
                  :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="购买方名称:" prop="buyerName">
              <el-input v-model="formData.buyerName" :clearable="true" placeholder="请输入购买方名称" />
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买方名称:" prop="buyerName">
              <el-select placeholder="请选择销售方名称" @change="buyerSelectChange" :modelValue="formData.buyerName" filterable>
                <el-option v-for="item in buyerNameOptions" :key="item.buyerIdNum" :label="item.buyerName" :value="item"
                  placeholder="请输入购买方名称" value-key="buyerIdNum" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买方税号:" prop="buyerIdNum">
              <el-input v-model="formData.buyerIdNum" :clearable="true" placeholder="请输入购买方税号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买方账号:" prop="buyerBankAccNum">
              <el-input v-model="formData.buyerBankAccNum" :clearable="true" placeholder="请输入购买方账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注:" prop="remark">
              <el-input v-model="formData.remark" type="textarea" autosize :clearable="true" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="备注:" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :clearable="true" placeholder="请输入备注" />
        </el-form-item> -->
        <!-- <el-form-item label="回写发票号:" prop="eiId">
          <el-input v-model="formData.eiId" :clearable="true" placeholder="请输入回写发票号" />
        </el-form-item> -->
        <!-- <el-form-item label="创建者:" prop="createdBy">
          <el-input v-model.number="formData.createdBy" :clearable="true" placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="更新者:" prop="updatedBy">
          <el-input v-model.number="formData.updatedBy" :clearable="true" placeholder="请输入更新者" />
        </el-form-item> -->

        <!-- <el-button v-show="formData.sellerName != ''" type="primary" @click="addItem">新增</el-button> -->
        <el-button v-show="formData.sellerName != '' && !isDisabled" type="primary"
          @click="OpenDetailForm">新增</el-button>

        <!-- <el-table :data="detailMultipleSelection" style="width: 100%" :cell-style="{ textAlign: 'center' }" -->
        <el-table :data="formData.items" style="width: 100%" :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ 'text-align': 'center' }" border show-overflow-tooltip show-summary
          :summary-method="getSummaries">
          <!-- <el-table-column label="规格" width="180">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>
                  <el-popover effect="light" trigger="hover" placement="top" width="auto">
                    <template #default>
                      <div>{{ scope.row.spec_mod }}</div>
                    </template>
                    <template #reference>
                      <el-select v-model="scope.row.ID" filterable remote reserve-keyword placeholder="请输入规格"
                        :remote-method="remoteMethod" :loading="Availableloading"
                        @change="handleSpecChange(scope.row, $event)">
                        <el-option v-for="item in RemainingAvailableTermSearchlist" :key="item.ID"
                          :label="item.Spec_Mod" :value="item.ID" />
                      </el-select>
                    </template>
                  </el-popover>

                </span>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column label="规格">
            <template #default="scope">
              <el-popover effect="light" trigger="hover" placement="top" width="auto">
                <template #default>
                  <div>{{ scope.row.spec_mod }}</div>
                </template>
                <template #reference>
                  {{ scope.row.spec_mod }}
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="项目名称">
            <template #default="scope">
              <el-popover effect="light" trigger="hover" placement="top" width="auto">
                <template #default>
                  <div>{{ scope.row.item_name }}</div>
                </template>
                <template #reference>
                  {{ scope.row.item_name }}
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template #default="scope">
              {{ scope.row.mea_units }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="数量" width="180">
            <template #default="scope">
              <el-input-number v-model="scope.row.Quantity" :precision="2" :step="0.1"  prop="items.Quantity"/>
            </template>
          </el-table-column> -->
          <el-table-column label="数量" width="180">
            <template #default="scope">
              <!-- <el-form-item :prop="'items.' + scope.$index + '.Quantity'" :rules="rule['items.Quantity']">
                <el-input-number v-model="scope.row.Quantity" :precision="2" :step="0.1" />
              </el-form-item> -->
              <el-input-number v-model="scope.row.quantity" :precision="3" :step="0.1" />
            </template>
          </el-table-column>
          <el-table-column label="单价(含税)" width="180">
            <template #default="scope">
              <el-tooltip
                :visible="scope.row.un_price < formatValue(scope.row.total_tax_included_amount, scope.row.Quantity)"
                effect="light" placement="top">
                <template #content>
                  <span style="color: red;">低于进项单价</span>
                </template>
                <el-input-number v-model="scope.row.un_price" :precision="2" :step="0.1" />
              </el-tooltip>
              <!-- <el-input-number v-model="scope.row.Un_Price" :precision="2" :step="0.1" /> -->
            </template>
          </el-table-column>
          <el-table-column label="金额(含税)">
            <template #default="scope">
              {{ formatJineValue(scope.row.un_price, scope.row.quantity, scope) }}
            </template>

          </el-table-column>
          <el-table-column label="进项单价(含税)">
            <template #default="scope">
              {{ formatValue(scope.row.total_tax_included_amount, scope.row.Quantity) }}
            </template>
            <!-- {{ value.Un_Price }} -->

          </el-table-column>
          <el-table-column label="进项金额(含税)">
            <template #default="scope">{{ formatAmountValue(scope.row.total_tax_included_amount,
              scope.row.quantity, scope.row.Quantity) }}</template>

          </el-table-column>
          <el-table-column label="盈利情况">
            <template #default="scope">
              {{ getProfit(scope) }}
            </template>

          </el-table-column>
          <el-table-column label="操作" v-if="!isDisabled">
            <template #default="scope">
              <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
                Edit
              </el-button> -->
              <el-button size="small" type="danger" @click="handleDelete(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
    </el-dialog>


    <el-dialog destroy-on-close width="70%" v-model="detailFormVisible" :show-close="false"
      :before-close="CloseDetailForm" :close-on-click-modal="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ type === 'create' ? '新增' : '编辑' }}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="SaveDetailForm">保 存</el-button>
            <el-button @click="CloseDetailForm">取 消</el-button>
          </div>
        </div>
      </template>

      <div>
        <div class="gva-search-box">
          <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule"
            @keyup.enter="onSubmit">
            <el-form-item label="创建日期" prop="createdAt">
              <template #label>
                <span>
                  创建日期
                  <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                    <el-icon>
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </span>
              </template>
              <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期"
                :disabled-date="time => searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
              —
              <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期"
                :disabled-date="time => searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
            </el-form-item>

            <el-form-item label="发票号码" prop="invoiceId">
              <el-input v-model="searchInfo.invoiceId" placeholder="搜索条件" />
            </el-form-item>
            <el-form-item label="商品名称" prop="itemName">
              <el-input v-model="searchInfo.itemName" placeholder="搜索条件" />
            </el-form-item>
            <el-form-item label="规格型号" prop="specMod">
              <el-input v-model="searchInfo.specMod" placeholder="搜索条件" />
            </el-form-item>

            <template v-if="showAllQuery">
              <!-- 将需要控制显示状态的查询条件添加到此范围内 -->
            </template>

            <el-form-item>
              <el-button type="primary" icon="search" @click="detailOnSubmit">查询</el-button>
              <el-button icon="refresh" @click="detailOnReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="gva-table-box">
          <div class="gva-btn-list flex-end">
            <!-- <el-button v-auth="btnAuth.add" type="primary" icon="plus" @click="openDialog()">新增</el-button>
            <el-button v-auth="btnAuth.batchDelete" icon="delete" style="margin-left: 10px;"
              :disabled="!multipleSelection.length" @click="onDelete">删除</el-button> -->
            <span>剩余未开票金额合计:{{ unlicensedAmount }}</span>

          </div>
          <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="detailTableData"
            row-key="invoice_item_id" @selection-change="detailHandleSelectionChange" show-overflow-tooltip border>
            <el-table-column type="selection" width="55" :reserve-selection="true" />

            <el-table-column align="left" label="日期" prop="request_time" width="180">
              <template #default="scope">{{ formatDate(scope.row.request_time) }}</template>
            </el-table-column>

            <!-- <el-table-column align="left" label="发票号码" prop="e_iid" /> -->
            <el-table-column align="left" label="商品名称" prop="item_name" />
            <el-table-column align="left" label="规格型号" prop="spec_mod" />
            <el-table-column align="left" label="计量单位" prop="mea_units" />
            <el-table-column align="left" label="数量" prop="quantity" />
            <el-table-column align="left" label="进项单价（含税）" width="180">
              <template #default="scope">
                {{ formatValue(scope.row.total_tax_included_amount, scope.row.quantity) }}
              </template>
            </el-table-column>
            <el-table-column align="left" label="金额" prop="amount" />
            <el-table-column align="left" label="税率" prop="tax_rate" />
            <el-table-column align="left" label="税额" prop="com_tax_am" />
            <el-table-column align="left" label="含税金额" prop="total_tax_included_amount" />
            <el-table-column align="left" label="税收分类编码" prop="tax_classification_code" />
          </el-table>
          <div class="gva-pagination">
            <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="pageSize"
              :page-sizes="[3, 10, 30, 50, 100]" :total="total" @current-change="detailHandleCurrentChange"
              @size-change="detailHandleSizeChange" />
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true"
      :before-close="closeDetailShow" title="查看">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="销售方名称">
          {{ detailFrom.sellerName }}
        </el-descriptions-item>
        <el-descriptions-item label="购买方名称">
          {{ detailFrom.buyerName }}
        </el-descriptions-item>
        <el-descriptions-item label="购买方税号">
          {{ detailFrom.buyerIdNum }}
        </el-descriptions-item>
        <el-descriptions-item label="购买方账号">
          {{ detailFrom.buyerBankAccNum }}
        </el-descriptions-item>
        <el-descriptions-item label="备注">
          {{ detailFrom.remark }}
        </el-descriptions-item>
        <el-descriptions-item label="回写发票号">
          {{ detailFrom.eiId }}
        </el-descriptions-item>
        <el-descriptions-item label="创建者">
          {{ detailFrom.createdBy }}
        </el-descriptions-item>
        <el-descriptions-item label="更新者">
          {{ detailFrom.updatedBy }}
        </el-descriptions-item>
        <el-descriptions-item label="删除者">
          {{ detailFrom.deletedBy }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <el-dialog destroy-on-close v-model="taskDialogVisible" title="输入验证码">
      <el-input v-model="taskDialogData.captcha"></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="taskCaptchaSubmit">
            确定提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createInvoiceItemUsages,
  deleteInvoiceItemUsages,
  deleteInvoiceItemUsagesByIds,
  updateInvoiceItemUsages,
  findInvoiceItemUsages,
  getInvoiceItemUsagesList,
  getRemainingAvailableTerm,
  updateExamineStatus,
  invoicing,
  invoicingSmsCode,
  resendTask
} from '@/api/fapiao/invoiceItemUsages'
import {
  getOrganizationTree,
} from '@/plugin/organization/api/organization'

import {
  getBuyerInfoList
} from '@/api/fapiao/buyerInfo'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, filterDataSource, returnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted, computed } from 'vue'
// 引入按钮权限标识
import { useBtnAuth } from '@/utils/btnAuth'
import { useAppStore } from "@/pinia"

// 导出组件
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
import ExportExcelByIds from '@/components/exportExcel/exportExcelByIds.vue'
// 导入组件
import ImportExcel from '@/components/exportExcel/importExcel.vue'
// 导出模板组件
import ExportTemplate from '@/components/exportExcel/exportTemplate.vue'




defineOptions({
  name: 'InvoiceItemUsages'
})
// 按钮权限实例化
const btnAuth = useBtnAuth()

// 提交按钮loading
const btnLoading = ref(false)
const appStore = useAppStore()

// 控制更多查询条件显示/隐藏状态
const showAllQuery = ref(false)

// 产品可用项列表
const RemainingAvailableTerm = ref([])
const Availableloading = ref(false)
const RemainingAvailableTermSearchlist = ref([])
const value = ref({})
const remoteMethod = async (query) => {
  if (query) {
    Availableloading.value = true
    await getRemainingAvailableTermData()
    setTimeout(() => {
      Availableloading.value = false
      RemainingAvailableTermSearchlist.value = RemainingAvailableTerm.value.filter((item) => {
        return item.Spec_Mod.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  } else {
    RemainingAvailableTermSearchlist.value = []
  }
  console.log(value.value)
  console.log(RemainingAvailableTermSearchlist.value)
  console.log(RemainingAvailableTerm.value)
}

onMounted(async () => {
  // await getRemainingAvailableTermData()
  // RemainingAvailableTerm.value = states.map((item) => {
  //   return { value: `value:${item}`, label: `label:${item}` }
  // })
})

const getRemainingAvailableTermData = async () => {
  await getRemainingAvailableTerm().then(res => {
    if (res.code === 0) {
      RemainingAvailableTerm.value = res.data
    }
  })
}

const formatValue = (total_tax_included_amount, Quantity) => {
  // 检查参数是否为空或非数字，并设置默认值为0
  const parsedTotal_tax_included_amount = parseFloat(total_tax_included_amount) || 0;
  const parsedQuantity = parseFloat(Quantity) || 0;

  // 如果数量为0，避免除以0的情况
  if (parsedQuantity === 0) {
    return 0;
  }

  const result = parsedTotal_tax_included_amount / parsedQuantity;
  const resultStr = result.toString();
  const decimalPart = resultStr.split('.')[1];

  if (decimalPart && decimalPart.length > 4) {
    return parseFloat(result.toFixed(6));
  } else {
    return parseFloat(result);
  }
}

const formatAmountValue = (total_tax_included_amount, quantity, Quantity) => {
  // 检查参数是否为空或非数字，并设置默认值为0
  const parsedTotal_tax_included_amount = parseFloat(total_tax_included_amount) || 0;
  const parsedRawQuantity = parseFloat(quantity) || 0;
  const parsedQuantity = parseFloat(Quantity) || 0;

  // 如果数量为0，避免除以0的情况
  if (parsedRawQuantity === 0 || parsedQuantity === 0) {
    return 0;
  }

  const result = formatValue(total_tax_included_amount, Quantity) * quantity;
  const resultStr = result.toString();
  const decimalPart = resultStr.split('.')[1];
  console.log(decimalPart)

  if (decimalPart && decimalPart.length > 4) {
    return parseFloat(result.toFixed(6));
  } else {
    return parseFloat(result);
  }
}

const formatJineValue = (un_price, quantity, scope, key = 'col') => {
  // 检查参数是否为空或非数字，并设置默认值为0
  const pun_price = parseFloat(un_price) || 0;
  const pquantity = parseFloat(quantity) || 0;

  // 如果数量为0，避免除以0的情况
  if (pun_price === 0 || pquantity === 0) {
    return 0;
  }

  const result = pun_price * pquantity;
  const resultStr = result.toString();
  const decimalPart = resultStr.split('.')[1];
  if (key == 'sum') {
    if (decimalPart && decimalPart.length > 4) {
      return parseFloat(result.toFixed(6));
    } else {
      return parseFloat(result);
    }
  }

  if (decimalPart && decimalPart.length > 4) {
    scope.row.amount = result.toFixed(6)
    return parseFloat(result.toFixed(6));
  } else {
    scope.row.amount = parseFloat(result)
    return parseFloat(result);
  }
}

const handleDelete = (index) => {
  // formData.value.items.splice(index, 1)
  // detailMultipleSelection.value.splice(index, 1)

  const deletedItem = formData.value.items[index];
  formData.value.items.splice(index, 1)
  // 从 selectedItems 中移除已删除的项
  selectedItems.value = selectedItems.value.filter(selected => selected.invoice_item_id !== deletedItem.invoice_item_id);
}

const addItem = () => {
  const newItem = {
    ID: '',
    Spec_Mod: '',
    Item_Name: '',
    Mea_Units: '',
    RawQuantity: 0,
    Quantity: 0,
    Un_Price: 0,
    Amount: 0,
    Com_Tax_Am: 0,
  }
  formData.value.items.push(newItem)
}



const handleSpecChange = (row, selectedId) => {
  // 根据选中的 ID 从 RemainingAvailableTerm.value 中找到对应的对象
  const selectedItem = RemainingAvailableTerm.value.find(item => item.ID === selectedId);

  if (selectedItem) {
    // 将找到的对象的其他属性值填充到相应的表格列中
    row.Spec_Mod = selectedItem.Spec_Mod;
    row.Item_Name = selectedItem.Item_Name;
    row.Mea_Units = selectedItem.Mea_Units;
    row.Amount = selectedItem.Amount;
    row.RawQuantity = selectedItem.Quantity;
    row.Com_Tax_Am = selectedItem.Com_Tax_Am;

  }
}


// 多选数据
const detailMultipleSelection = ref([])
// 多选
const detailHandleSelectionChange = (val) => {
  detailMultipleSelection.value = val
}


// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  sellerName: '',
  buyerName: '',
  buyerIdNum: '',
  buyerBankAccNum: '',
  remark: '',
  items: [],
  eiId: undefined,
  createdBy: undefined,
  updatedBy: undefined,
  deletedBy: undefined,
})



// 验证规则
const rule = reactive({
  sellerName: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  buyerName: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  buyerIdNum: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  buyerBankAccNum: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  items: [{
    type: 'array',
    required: true,
    message: '至少需要一个项目',
    trigger: 'change'
  }],
  'items.quantity': [{
    required: true,
    message: '数量不能为空',
    trigger: ['input', 'blur'],
  },
  {
    type: 'number',
    message: '数量必须是数字',
    trigger: ['input', 'blur'],
  }
  ],
})

const searchRule = reactive({
  createdAt: [
    {
      validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change'
    }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const detailTableData = ref([])
const searchInfo = ref({})
const examineTypeName = {
  0: '待审核',
  1: '提交开票',
  2: '已提交',
  3: '开票完成'
}
const taskName = {
  '-1': '开票出错',
  '-2': '重试',
  1: '成功',
  2: '执行中',
  3: '验证码上传'
}
const taskDialogVisible = ref(false)
const taskDialogData = ref({ task_id: '', captcha: '' })
// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const detailOnReset = () => {
  searchInfo.value = {}
  detailGetTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return
    page.value = 1
    getTableData()
  })
}

const detailOnSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return
    page.value = 1
    detailGetTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
// 分页
const detailHandleSizeChange = (val) => {
  pageSize.value = val
  detailGetTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
// 修改页面容量
const detailHandleCurrentChange = (val) => {
  page.value = val
  detailGetTableData()
}
// 销售方下拉菜单
const sellerNameSelectOptions = ref([])
const getSellerNameOptions = async () => {
  const options = await getOrganizationTree()
  sellerNameSelectOptions.value = options.data?.map(i => { return { label: i.name, value: String(i.ID) } })
}
// 查询
const detailGetTableData = async () => {
  const table = await getRemainingAvailableTerm({ page: page.value, pageSize: pageSize.value, ...searchInfo.value, seller: formData.value.sellerName })
  if (table.code === 0) {
    // detailTableData.value = table.data.list
    // 过滤掉已选择的项
    detailTableData.value = table.data.list?.filter(item => !selectedItems.value.some(selected => selected.invoice_item_id === item.invoice_item_id));
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

// 查询
const getTableData = async () => {
  const table = await getInvoiceItemUsagesList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    table.data.list.forEach(item => {
      if (item?.task) {
        item.eiId = item.task?.invoice_list_electronic_invoice_no
        item.pdf = item.task?.pdf
        item.xml = item.task?.xml
      }
    })

    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()


const examineBtnClick = async (scope, state) => {
  let data
  if (scope.row.examine == 1) {
    // 提交开票申请
    data = await invoicing({ ID: scope.row.ID })
  }
  else {
    data = await updateExamineStatus({ ID: scope.row.ID, examine: `${state}` })
  }
  if (data.code == 0) {
    ElMessage({
      message: data.msg,
      type: 'success',
    })
    getTableData()
  }

  getTableData()
}
const taskBtnClick = async (scope) => {
  if (!scope.row?.task) return
  if (scope.row?.task.task_state == 3) {
    taskDialogData.value.task_id = scope.row?.task?.task_id
    taskDialogVisible.value = true
  }
  if (scope.row?.task.task_state == -2) {
    const data = await resendTask({ task_id: scope.row?.task?.task_id })
    if (data.code == 0) {
      ElMessage({
        message: data.msg,
        type: 'success',
      })
    }
  }
  getTableData()
}
const taskCaptchaSubmit = async () => {
  const data = await invoicingSmsCode({ ...taskDialogData.value })
  if (data.code == 0) {
    ElMessage({
      message: data.msg,
      type: 'success',
    })
  }
  taskDialogVisible.value = false
  getTableData()

}
// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteInvoiceItemUsagesFunc(row)
  })
}

// 多选删除
const onDelete = async () => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const IDs = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
      multipleSelection.value.map(item => {
        IDs.push(item.ID)
      })
    const res = await deleteInvoiceItemUsagesByIds({ IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateInvoiceItemUsagesFunc = async (row, disabled = false) => {
  const res = await findInvoiceItemUsages({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    formData.value.items = res.data.items.map(item => {
      return {
        ...item,
        Quantity: item.raw_quantity,
      }
    })
    dialogFormVisible.value = true
    isDisabled.value = disabled
  }
}


// 删除行
const deleteInvoiceItemUsagesFunc = async (row) => {
  const res = await deleteInvoiceItemUsages({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)
const isDisabled = ref(false)

const detailFormVisible = ref(false)


// 获取购买方列表
const buyerNameOptions = ref([])
const getbuyerNameOptions = async () => {
  const options = await getBuyerInfoList()
  buyerNameOptions.value = options.data.list
}
const buyerSelectChange = (value) => {
  formData.value.buyerName = value.buyerName
  formData.value.buyerIdNum = value.buyerIdNum
  formData.value.buyerBankAccNum = value.buyerBankAccNum
}
// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
  isDisabled.value = false
  selectedItems.value = []
  getSellerNameOptions()
  getbuyerNameOptions()
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    sellerName: '',
    buyerName: '',
    buyerIdNum: '',
    buyerBankAccNum: '',
    remark: '',
    items: [],
    eiId: undefined,
    createdBy: undefined,
    updatedBy: undefined,
    deletedBy: undefined,
  }
}



const OpenDetailForm = () => {
  detailFormVisible.value = true
  detailGetTableData()
}
const CloseDetailForm = () => {
  detailFormVisible.value = false
}

// 未开票金额总计
const unlicensedAmount = computed(() => {
  return detailMultipleSelection.value.reduce((a, b) => a + Number(b.total_tax_included_amount), 0)
})

const selectedItems = ref([]);
const SaveDetailForm = () => {
  detailFormVisible.value = false
  // formData.value.items = detailMultipleSelection.value

  // 遍历 detailMultipleSelection.value 并将每个对象的 quantity 设置为 0
  const updatedItems = detailMultipleSelection.value.map(item => {
    return {
      ...item,
      un_price: formatValue(item.total_tax_included_amount, item.quantity),
      Quantity: item.quantity,
    }
  })

  formData.value.items = [...formData.value.items, ...updatedItems];
  // 将已选择的项添加到 selectedItems 数组中
  selectedItems.value = [...selectedItems.value, ...updatedItems];
}

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {

    if (index == 0) {
      sums[index] = '合计'
    }
    if (index === 5) { // 第6列（从0开始计数）
      sums[index] = data.reduce((sum, item) => sum + Number(formatJineValue(item.un_price, item.quantity, item, 'sum')), 0);
    }
    else if (index != 0 && index != 5) {
      sums[index] = '—';
    }
  });
  return sums;
};
const getProfit = (scope) => {
  const profit = formatJineValue(scope.row.un_price, scope.row.quantity, scope) - formatAmountValue(scope.row.total_tax_included_amount,
    scope.row.quantity, scope.row.Quantity)
  scope.row['profit'] = profit
  return profit
}

// 弹窗确定
const enterDialog = async () => {
  btnLoading.value = true
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return btnLoading.value = false
    let res
    const formatKey = ['invoice_item_id', 'quantity', 'un_price', 'amount', 'profit']
    const requestData = { ...formData.value, items: [] }
    requestData.items = formData.value.items.map(i => {
      const returnData = {}
      Object.keys(i).forEach(t => {
        if (formatKey.includes(t)) {
          returnData[t] = Number(i[t])
        }
      })
      return returnData
    })

    switch (type.value) {
      case 'create':
        res = await createInvoiceItemUsages(requestData)
        break
      case 'update':
        res = await updateInvoiceItemUsages(requestData)
        break
      default:
        res = await createInvoiceItemUsages(requestData)
        break
    }
    btnLoading.value = false
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const detailFrom = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findInvoiceItemUsages({ ID: row.ID })
  if (res.code === 0) {
    detailFrom.value = res.data
    detailFrom.value.items = res.data.items.map(item => {
      return {
        ...item,
        Quantity: item.raw_quantity,
      }
    })
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailFrom.value = {}
}


</script>

<style scoped lang="scss">
.gva-btn-list.flex-end {
  justify-content: flex-end;
}

:deep(.el-table__footer) .cell {
  text-align: center;
}
</style>
